/**
 * mysql 类封装
 */

module.exports = function Mysql(){
    if (typeof arguments.callee.instance instanceof Object){
        return arguments.callee.instance;
    }

    var Q = require("q");
    var mysql = require('mysql');
    var pool  = mysql.createPool({
        host     : 'localhost',
        user     : 'root',
        password : '123456'
    });

    /**
     *
     * @returns {promise|*|promise}
     */
    this.getConnection = function(){
        var defered = Q.defer();
        pool.getConnection(function(err,connection){
           if(err){
               defered.reject(err)
           }else{
               defered.resolve(connection)
               connection.release();
           }
        });
        return defered.promise;
    }

    /**
     *
     * @param sql
     * @returns {promise|*|promise}
     */
    this.query = function(sql){

        var args = new Array();
        for(var i in arguments){
            args.push(arguments[i]);
        }
        var defered = Q.defer();
        this.getConnection().then(
            function(connection){
                try{
                    var callback = function(err,rows){
                        if(err){
                            defered.reject(err);
                            connection.release();
                        }else{
                            defered.resolve(rows);
                            connection.release();
                        }
                    };
                    args.push(callback);
                    connection.query.apply(connection,args);
                }catch (e){
                    defered.reject(e);
                }
            },
            function(err){
                defered.reject(err);
            }
        );
        return defered.promise;
    }

    /**
     *
     * @param sql
     * @returns {*|promise|*|promise|query|query}
     */
    this.insert = function(sql){
        return this.query.apply(this,arguments).then(function(data){
            data.lastInsertId = data.insertId + data.affectedRows - 1;
            return data;
        },function(err){
            throw new Error(err);
        });
    }

    /**
     *
     * @param table String
     * @param json Object
     * @returns {promise|*|promise}
     */
    this.insertJson = function(table,json){
        if(! (json instanceof Object)  ){
            var defered = Q.defer();
            defered.reject(new Error("第二个参数必须是JSON对象"))
            return defered.promise;
        }

        var filedArr = new Array();
        var valueArr = new Array();
        var replaceArr = new Array();
        for(var filed in json){
            filedArr.push(filed);
            valueArr.push(json[filed]);
            replaceArr.push("?");
        }
        var sql = "INSERT INTO " +table+ "(" +filedArr.join(",")+ ") VALUES(" +replaceArr.join(",")+ ")";
        return this.insert(sql,valueArr);
    }

    /**
     * 插入多条记录
     * @param table
     * @param arrJson
     * @returns {promise|*|promise}
     */
    this.insertMoreJson = function(table,arrJson){
        if(! (arrJson instanceof Array)  ){
            var defered = Q.defer();
            defered.reject(new Error("第二个参数必须是JSON对象组成的数组"))
            return defered.promise;
        }

        var filedContinue =  false;
        var valueArr = new Array();
        var filedArr = new Array();
        var replaceArr = new Array();
        var arrLen = arrJson.length;
        for(var i=0;i<arrLen;i++){
            var replaceSubArr = new Array();
            for(var filed in arrJson[i]){
                if(!filedContinue){
                    filedArr.push(filed);
                }
                valueArr.push(arrJson[i][filed]);
                replaceSubArr.push("?");
            }
            replaceArr.push( "(" + replaceSubArr.join(",") + ")" );
            filedContinue = true;
        }
        var sql = "INSERT INTO " +table+ "(" +filedArr.join(",")+ ") VALUES " +replaceArr.join(",");
        return this.insert(sql,valueArr);
    }

    /**
     * select
     * @param sql
     * @returns {*|promise|*|promise|query|query}
     */
    this.select = function(sql){
        return this.query.apply(this,arguments);
    }

    /**
     * 返回影响的记录数
     * @param sql
     * @returns {promise|*|promise}
     */
    this.update = function(sql){
        return this.query.apply(this,arguments).then(
            function(data){
                return data.changedRows;
            },
            function(err){
                throw new Error(e);
            }
        );
    }

    this.delete = function(sql){
        return this.query.apply(this,arguments).then(
            function(data){
                return data.affectedRows;
            },
            function(err){
                throw new Error(e);
            }
        );
    }

    this.close = function(){

    }

    arguments.callee.instance = this;
}